const express = require('express')
const router = express.Router()
const crypto = require('crypto')
const ws = require('ws')
const RoleModel = require('../model/RoleModel')
const ChatAIModel = require('../model/ChatAIModel')
// 模型主机和路径
const { host, path } = require('../config/ai/api_url')
// APISecret
const APISecret = require('../config/ai/api_secret')
// APIKey
const APIKey = require('../config/ai/api_key')
// APPID
const APPID = require('../config/ai/appId')

// chatAI 接口
router.post('/chatAI', async (req, res) => {
    res.setHeader('Content-Type', 'text-event-stream')
    res.setHeader('Cache-Control', 'no-cache')
    res.setHeader('Connection', 'keep-alive')

    const { _id, userId, contents, model } = req.body
    let { temperature, content } = model ? JSON.parse(model) : {}
    let data = [...JSON.parse(contents)]
    if (model && content) {
        data.unshift({
            role: 'system',
            content
        })
    }
    data = data.slice(0, 20)

    // 获取当前时间的 GMT 字符串
    const dateString = new Date().toGMTString()

    // 构建用于签名的请求头
    let tmp = `host: ${host}\ndate: ${dateString}\nGET ${path} HTTP/1.1`

    let signature = crypto
        .createHmac('sha256', APISecret)
        .update(tmp)
        .digest('base64')

    const authorization_origin = `api_key="${APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`

    // 将授权信息编码为 Base64 格式
    let buff = Buffer.from(authorization_origin)
    const authorization = buff.toString('base64')

    // 构建访问星火 API 的 WebSocket URL
    const signUrl = `wss://${host}${path}?authorization=${authorization}&date=${encodeURIComponent(dateString)}&host=${host}`

    // 创建 WebSocket 连接
    let sock = new ws(signUrl)

    let questionValue = ''

    // 当连接打开时发送聊天请求
    sock.on('open', () => {
        sock.send(
            JSON.stringify({
                header: {
                    app_id: APPID,
                    uid: userId
                },
                parameter: {
                    chat: {
                        domain: 'generalv3',
                        temperature,
                        max_tokens: 1024,
                    },
                },
                payload: {
                    message: {
                        text: data,
                    },
                }
            })
        )
    })

    // 监听连接的错误事件
    sock.on('error', (err) => {
        res.write(JSON.stringify({ status: false }))
    })

    // 监听消息事件，处理 API 响应
    sock.on('message', (data) => {
        // 解析 API 响应的 JSON 数据
        const obj = JSON.parse(data)
        // 提取文本消息
        const text = obj.payload.choices.text[0].content
        // 将文本消息拼接到问题值中
        questionValue += text

        res.write(JSON.stringify({
            status: true,
            content: text
        }))
    })

    // 监听连接关闭事件
    sock.on('close', async () => {
        // 将历史记录存数据库
        try {
            let AIModel = await ChatAIModel.findOne({ _id, userId })
            if (!AIModel || !AIModel.contents.length === 0) {
                AIModel = new ChatAIModel({
                    userId,
                    contents: [
                        ...JSON.parse(contents),
                        {
                            role: 'assistant',
                            content: questionValue
                        }
                    ],
                    ...(model ? { model: JSON.parse(model) } : {})
                })
            } else {
                let historys = contents.replace('\n', '\\n')
                AIModel.contents.push(
                    JSON.parse(historys)[JSON.parse(historys).length - 1],
                    {
                        role: 'assistant',
                        content: questionValue
                    }
                )
                AIModel.markModified('contents')
            }
            let result = await AIModel.save()
            res.write(JSON.stringify({ status: false, content: result }))
        } catch (error) {
            res.write(JSON.stringify({ status: false }))
        }
    })
})

// 获取角色列表接口
router.get('/get/role/list', async (req, res) => {
    const { userId } = req.query
    try {
        let list = await RoleModel.find({ userId })
        res.json({
            status: 200,
            msg: 'success',
            data: list
        })
    } catch (error) {
        res.json({
            status: 404,
            msg: '服务器错误',
            data: []
        })
    }
})

// 创建角色接口
router.post('/create/role', async (req, res) => {
    const { userId, role, describe, content } = req.body
    try {
        await RoleModel.create({
            userId,
            role,
            describe,
            content
        })
        res.json({
            status: 200,
            msg: '添加成功'
        })
    } catch (error) {
        res.json({
            status: 404,
            msg: '添加失败'
        })
    }
})

// 修改角色接口
router.post('/update/role', async (req, res) => {
    const { id, userId, role, describe, content } = req.body
    try {
        await RoleModel.updateOne({ _id: id }, {
            userId,
            role,
            describe,
            content
        })
        res.json({
            status: 200,
            msg: '修改成功'
        })
    } catch (error) {
        res.json({
            status: 404,
            msg: '修改失败'
        })
    }
})

// 删除角色接口
router.get('/delete/role', async (req, res) => {
    const { _id } = req.query
    try {
        await RoleModel.deleteOne({ _id })
        res.json({
            status: 200,
            msg: '删除成功'
        })
    } catch (error) {
        res.json({
            status: 404,
            msg: '删除失败'
        })
    }
})

// 获取历史记录列表接口
router.get('/get/history/list', async (req, res) => {
    const { userId } = req.query
    try {
        let list = await ChatAIModel.find({ userId }).sort({ createTime: -1 })
        let data = list.map(item => {
            return {
                _id: item._id,
                config: {
                    content: item.model.content,
                    temperature: item.model.temperature
                },
                content: item.contents[0].content
            }
        })
        res.json({
            status: 200,
            msg: 'success',
            data: data
        })
    } catch (error) {
        res.json({
            status: 404,
            msg: '服务器错误'
        })
    }
})

// 获取对话详情接口
router.get('/get/talk/detail', async (req, res) => {
    const { userId, _id } = req.query
    try {
        let data = await ChatAIModel.findOne({ _id, userId })
        res.json({
            status: 200,
            msg: 'success',
            data: data
        })
    } catch (error) {
        res.json({
            status: 404,
            msg: '服务器错误'
        })
    }
})

// 删除对话记录接口
router.get('/delete/talk', async (req, res) => {
    const { _id, userId } = req.query
    try {
        await ChatAIModel.deleteOne({ _id, userId })
        res.json({
            status: 200,
            msg: '删除成功'
        })
    } catch (error) {
        res.json({
            status: 404,
            msg: '删除失败'
        })
    }
})

module.exports = router